package rensoft.android.lang;

import static rensoft.java.lang.Lang.doLater;

import rensoft.java.lang.Run;
import rensoft.java.net.UrlBuilder;

public class Request extends RequestBase {

  private final String serverUrl;
  private String response;

  public Request(String serverUrl) {
    this.serverUrl = serverUrl;
  }

  public String getResponse() {
    return response;
  }

  public void run() {
    try {
      final String response = getResponseString(getUrl().toString());
      doLater(new Run() {
        public void run() {
          onRequestLoaded(response);
          onProcessDone();
        }
      });
    } catch (final Exception e) {
      doLater(new Run() {
        public void run() {
          requestFailed(e);
          onProcessDone();
        }
      });
    }

  }

  @Override
  protected String getServerUrl() {
    return serverUrl;
  }

  @Override
  protected void onUrlCreated(UrlBuilder url) {}

  private void onProcessDone() {
    fire(eventDone);
  }

  private void onRequestLoaded(String response) {
    this.response = response;
    fire(eventLoaded);
  }

  private void requestFailed(Exception e) {
    fire(eventFailed);
  }

}
